<template>
<view>
<!--pages/productDetail/index.wxml-->


<view class="top_tab">
  <view class="top_tab_item" @tap="switchState" data-type="1">
    <text :class="(showInfo?'active':'')">主要</text>
  </view>
  <view class="top_tab_item" @tap="switchState" data-type="0">
    <text :class="(!showInfo?'active':'')">详情</text>
  </view>
</view>
<view class="container" v-if="showInfo">
  <view class="SwiperContainer">
    <swiper class="SwiperIndex" indicator-dots="true" autoplay="true" indicator-color="#dcdcdc" indicator-active-color="#bebebe" interval="5000" duration="500" @change="swiperChange">
      <block v-for="(item, swiper) in productData.images" :key="swiper">
        <swiper-item :data-imageUrl="productData.images" :data-index="index" @tap="lookBigImage">
          <image mode="aspectFit" :src="item.imagePath + '?x-oss-process=style/normal'"></image>
        </swiper-item> 
      </block>
    </swiper>
    <!-- <view class='swiperItemIndex'>{{swiperIndex}}/{{totalImg}}</view> -->
    <block v-if="productData.productInfo.promotionBean">
      <view class="timeCountDownBg" :style="'background:linear-gradient(116deg,' + setting.platformSetting.secondColor + ' 0%,' + color + ' 100%);'" v-if="productData.productInfo.promotionBean.promotionStatus!=2"></view>
      <view class="timeCountDownBg" style="background:linear-gradient(116deg,#eee 0%,#999 100%);" v-else></view>
      <view class="timeCountDown" v-if="productData.productInfo.promotionBean">
        <view class="promotionTitle" v-if="productData.productInfo.promotionBean.promotionStatus==1">
          <image class="timeLeftImg" src="https://image1.sansancloud.com/xianhua/2019_1/28/15/11/13_55.jpg"></image>
          <text class="promotionName">{{productData.productInfo.promotionBean.name}}</text>
        </view>
        <view class="promotionTitle" v-if="productData.productInfo.promotionBean.promotionStatus==2">
          <image class="timeLeftImg" src="https://image1.sansancloud.com/xianhua/2019_1/28/15/11/13_60.jpg"></image>
          <text class="promotionName">{{productData.productInfo.promotionBean.name}}</text>
        </view>
        <view class="promotionTitle" v-if="productData.productInfo.promotionBean.promotionStatus==0">
          <image class="timeLeftImg" src="https://image1.sansancloud.com/xianhua/2019_1/28/15/11/13_55.jpg"></image>
          <text class="promotionName">{{productData.productInfo.promotionBean.name}}</text>
        </view>
        <view class="timeItem">
          <text class="timeText" v-if="productData.productInfo.promotionBean.promotionStatus==1">距结束</text>
          <text class="timeText" v-if="productData.productInfo.promotionBean.promotionStatus==2">已结束</text>
          <text class="timeText" v-if="productData.productInfo.promotionBean.promotionStatus==0">距开始</text>
          <time-component ref="productTimeOne" v-if="productData!=null&&productData.productInfo.promotionBean.promotionStatus==0&&!clearTimeState" :receiveData="productData.productInfo.promotionBean.startDate"></time-component>
          <time-component ref="productTimeTwo" v-if="productData!=null&&productData.productInfo.promotionBean.promotionStatus==1&&!clearTimeState" :receiveData="productData.productInfo.promotionBean.endDate"></time-component>
        </view>
      </view>
    </block>
  </view>  
  <!-- 产品详细内容 -->
  <view class="product_info">
    <text class="product_name">{{productData.productInfo.name}}</text>
    <text class="product_description">{{productData.productInfo.description||"广告语位置"}}</text>
    <view class="sale_tag_list" v-if="productData.productInfo.itemSpecialSaleType!=0">
      <view class="sale_tag" v-if="productData.productInfo.itemSpecialSaleType==1">
        <text class="sale_tag_title">满减</text>
        <text class="sale_tag_value">满{{productData.productInfo.itemSpecialSaleValue1}}元减{{productData.productInfo.itemSpecialSaleValue2}}元</text>
      </view>
      <view class="sale_tag" v-if="productData.productInfo.itemSpecialSaleType==2">
        <text class="sale_tag_title">买赠</text>
        <text class="sale_tag_value">买{{productData.productInfo.itemSpecialSaleValue1}}件赠{{productData.productInfo.itemSpecialSaleValue2}}件</text>
      </view>
      <view class="sale_tag" v-if="productData.productInfo.itemSpecialSaleType==3">
        <text class="sale_tag_title">限购</text>
        <text class="sale_tag_value">限购{{productData.productInfo.itemSpecialSaleValue1}}件</text>
      </view>
    </view>
    <view class="product_base_info">
      <view class="product_unit"><text>{{productData.productInfo.unitShow}}</text></view>
      <view class="product_price_info">
        <text>￥</text>
        <text class="product_price" v-if="productData.productInfo.promotionBean">{{productData.productInfo.promotionPrice}}</text>
        <text class="product_price" v-else>{{productData.productInfo.price}}</text>
        <view class="product_tag_price" v-if="productData.productInfo.tagPrice>productData.productInfo.price">
          <text>/</text><text class="value">￥{{productData.productInfo.tagPrice}}</text>
        </view>
      </view>
      <view class="product_brand"><text>{{productData.productInfo.brandName}}</text></view>
    </view>
  </view>
  <view class="btn_tab">
    <view class="btn_tab_item" :data-itemId="productData.productInfo.productId" @click.stop="selectFavouriteType">
        <!-- productData.productInfo.favorite==0?'addToFavourite':'removeFavourite' -->
      <image v-if="productData.productInfo.favorite==1" class="btn_tab_icon" src="https://image1.sansancloud.com/xianhua/2019_4/1/13/47/58_785.jpg?x-oss-process=style/preview_120"></image>
      <image v-if="productData.productInfo.favorite==0" class="btn_tab_icon" src="https://image1.sansancloud.com/xianhua/2019_4/1/13/52/1_278.jpg?x-oss-process=style/preview_120"></image>
      <text v-if="productData.productInfo.favorite==1">已收藏</text>
      <text v-if="productData.productInfo.favorite==0">收藏</text>
    </view>
    <view class="btn_tab_item" @tap="showWay">
      <image class="btn_tab_icon" src="https://image1.sansancloud.com/xianhua/2019_4/1/13/47/58_484.jpg?x-oss-process=style/preview_120"></image>
      <text>推荐</text>
      <view class="showList" v-if="showWayState">
        <button class="showItem btn" @click.stop="showPoster">
          <image class="sharaPosterIcon" src="https://image1.sansancloud.com/sansancloud/2018_9/10/10/4/26_910.jpg?x-oss-process=style/preview_120"></image>
          <text>生成海报</text>
        </button>
        <button class="showItem btn" open-type="share">
          <image class="sharaPosterIcon" src="https://image1.sansancloud.com/sansancloud/2018_9/10/10/16/1_467.jpg?x-oss-process=style/preview_120"></image>
          <text>分享页面</text>
        </button>
      </view>
    </view>
  </view>
  <view class="interval"></view>
  <!-- 首页组件-私有产品详情装饰-->
  <view style="margin-top:20rpx;">
    <custom-page-index-component :receiveData="sendProductData"></custom-page-index-component>
  </view>

  <!-- 首页组件-公共产品详情装饰-->
  <custom-page-index-component :receiveData="sendIndexData"></custom-page-index-component>
</view>

  
<view class="loading" v-if="!showInfo">
  <text>下拉回到顶部</text>
</view>
<!-- 富文本 -->
<view class="tab_detail_container" v-if="!showInfo">
  <view class="wxParseHtmlContainer"> 
    <!-- <component is="init" :wxParseData="article.nodes"></component> -->
    <rich-text-component :receiveData="articleJsonData" v-if="articleJsonData"></rich-text-component>
  </view>
</view>

<view class="user_footer">
  <image class="user_footer_img" mode="aspectFit" src="https://image1.sansancloud.com/xianhua/2019_3/27/15/46/41_583.jpg"></image>
</view>
<view class="loading" v-if="showInfo">
    <text>{{loadingText}}</text>
  </view>
<!-- 底部按钮们 -->
<view class="bottomHeight"></view>
<view class="product_detail_bottom_container">
 <view class='left_bottom' :data-itemId="productData.productInfo.productId" @tap="toIndex">
   <image class="left_bottom_icon" mode="aspectFit" src="https://image1.sansancloud.com/xianhua/2019_11/20/14/38/47_682.jpg?x-oss-process=style/preview_120"></image>
   <text style="font-size:22rpx;color:#aaa">首页</text>
  </view> 
  <view class="left_bottom" @tap="toCart" data-link="milk_shopping_car_pages.html" v-if="!productData.productInfo.preOrderCustomFormId">
    <view class="cartNumber" :style="'background:' + color">{{countGood}}</view>
    <image class="left_bottom_icon" mode="widthFix" src="https://image1.sansancloud.com/xianhua/2019_11/20/14/39/19_841.jpg?x-oss-process=style/preview_120"></image>
    <text style="font-size:22rpx;color:#aaa">购物车</text>
  </view>
  <block v-if="!pintuanState">
    <view class="right_bottom addto font_08" data-way="cart" @tap="readyPay2" :style="' border: 2rpx solid ' + color + ';color:' + color" v-if="!productData.productInfo.preOrderCustomFormId">加入购物车</view>
    <!-- <view wx:else class='right_bottom'></view> -->
    <view :class="(productData.productInfo.preOrderCustomFormId?'w_540':'') + ' right_bottom bynow font_08'" data-way="buy" @tap="readyPay2" :style="'background-image:linear-gradient(to right,' + secondColor + ',' + color + ');box-shadow:0px 0px 6px 0px ' + color + ';'">
      <text v-if="productData.productInfo.preOrderCustomFormId">立即下单</text>
      <text v-else>立即购买</text>
    </view>
  </block>
  <block v-else>
    <view class="right_bottom addto font_08" data-way="pintuanOne" @tap="readyPay2" :style="' border: 2rpx solid ' + color + ';color: ' + color">单独购买</view>
  <view class="right_bottom bynow font_08" data-way="pintuanMore" @tap="readyPay2" :style="'background-image:linear-gradient(to right,' + secondColor + ',' + color + ');box-shadow:0px 0px 6px 0px ' + color + ';'">发起拼单</view>
  </block>
</view>

<posters-component :proId="proId" :shopId="shopId" :ewmImgUrl="qrCodeUrl" v-if="posterState" @closePoaster="getChilrenPoster"></posters-component> 
<pintuan-component :pintuanParam="pintuanParam" v-if="pintuanPopupState" @closePintuan="getChilrenPintuan" @goPintuan="readyPay2"></pintuan-component>
<measure-card-component v-if='showCount' :showCount="showCount" :productData='productData' :pintuanParams="pintuanParams" :byNowParams="byNowParams" :bindway="bindway" @closeCard="getCloseCardFun"></measure-card-component>
 <!-- <component is="measure_card2" :setting="minCount" :focusData="productData.productInfo" :measures="productData.measures" :byNowParams="byNowParams" :measurementJson="measurementJson" :type="bindway"></component> -->
</view>
</template>

<script>

import publicFun from '../../wxcomponents/public/publicFun.wxs'

export default {
  data() {
    return {
      setting: null,
      // setting 
      productData: null,
      // 商品数据 
      cart: null,
      countGood: 0,
      sysWidth: 320,
      //图片大小
      showCount: false,
      saleStrategyState: false,
      measuresState: false,
      positionState: false,
      attrsState: false,
      targs: [],
      posterState: false,
      pintuanPopupState: false,
      proId: '',
      shopId: '',
      bindway: 'cart',
      //点击的是加入购物车或者立即购买
      showState: 0,
      commitList: [],
      measurementJson: null,
      qrCodeUrl: "",
      haveMeasuresState: false,
      selectTypeData: null,
      swiperIndex: 1,
      totalImg: 0,
      pintuanId: 0,
      pintuanState: false,
      promotionState: false,
      pintuanListData: [],
      color: '',
      secondColor: "",
      clientNo: '',
      minCount: '1',
      sendIndexData: {},
      showInfo: true,
      showWayState: false,
      loadingText: "上拉查看详情",
      bottomState: true,
      byNowParams: {
        productId: '',
        itemCount: 1,
        shopId: '',
        cartesianId: '0',
        fromSource: 'mini',
        orderType: ''
      },
      pintuanParams: {
        pintuanCreateType: 0,
        pintuanRecordId: 0
      },
      dataFOr_getData: {
        id: '',
        addShopId: ''
      },
      pintuanParam: "",
      visiblePintuanNum: 0,
      sendProductData: "",
      swiperHeight: "",
      showGuigeType: false,
      articleJsonData: "",
      clearTimeState:false,
    };
  },

  props: {},
  onError: function (options) {
    console.log("on error!!!");
  },
  onLoad: function (options) {
    this.publicFun = publicFun;
    console.log('--------product----------', options);
    let that = this;
    that.setData({
      sysWidth: getApp().globalData.sysWidth,
      proId: options.id || options.productId,
      shopId: options.addShopId,
      clientNo: getApp().globalData.clientNo,
      color: getApp().globalData.setting.platformSetting.defaultColor,
      secondColor: getApp().globalData.setting.platformSetting.secondColor
    });
    let sendIndexData = JSON.stringify({
      title: 'noTitle',
      url: "productdetail",
      params: {
        pageObjectId: options.id || options.productId
      }
    });
    that.setData({
      sendIndexData: sendIndexData
    });
    let sendProductData = JSON.stringify({
      title: 'noTitle',
      url: "product_detail_" + (options.id || options.productId)
    });
    that.setData({
      sendProductData: sendProductData
    });
    console.log("商品id和店铺id", options);
    that.dataFOr_getData.id = options.id || options.productId, that.dataFOr_getData.addShopId = options.addShopId;
    that.setData({
      dataFOr_getData: that.dataFOr_getData
    });
    that.optionsData = options;
    that.getData(that.optionsData);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.setData({
      setting: getApp().globalData.setting
    });
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        console.log("===res.windowHeight===", res.windowHeight);
        that.setData({
          swiperHeight: res.windowHeight - 37
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that=this;
    if(that.clearTimeState){
      that.setData({clearTimeState:false})
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
      this.setData({clearTimeState:true})
      this.$refs.productTimeOne?this.$refs.productTimeOne.setShowTimeStateFun(true):'';
      this.$refs.productTimeTwo?this.$refs.productTimeTwo.setShowTimeStateFun(true):'';
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
      this.setData({clearTimeState:true})
      this.$refs.productTimeOne?this.$refs.productTimeOne.setShowTimeStateFun(true):'';
      this.$refs.productTimeTwo?this.$refs.productTimeTwo.setShowTimeStateFun(true):'';
    },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log("========下拉========");
    this.setData({
      loadingText: '上拉查看详情'
    });
    this.setData({
      showInfo: true,
      bottomState: true
    });
    wx.pageScrollTo({
      scrollTop: 0
    });
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this;
    console.log("========上拉触底========", that.bottomState);
    let bottomState = that.bottomState;

    if (bottomState) {
      setTimeout(function () {
        that.setData({
          showInfo: false,
          bottomState: false
        });
        wx.pageScrollTo({
          scrollTop: 0
        });
      }, 1000);
    } // this.setData({ showInfo: false })
    // wx.pageScrollTo({
    //   scrollTop: 0
    // })

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    console.log(res);
    let that = this;
    that.shareAppMessage(res);
  },
  methods: {
    /*轮播图下标*/
    swiperChange: function (e) {
      this.setData({
        swiperIndex: e.detail.current + 1
      });
    },
    showWay: function () {
      let that = this;

      if (that.showWayState) {
        this.setData({
          showWayState: false
        });
      } else {
        this.setData({
          showWayState: true
        });
      }
    },

    // 关闭海报
    getChilrenPoster(e) {
      let that = this;
      that.setData({
        posterState: false
      });
    },

    getChilrenPintuan(e) {
      let that = this;
      that.setData({
        pintuanPopupState: false
      });
    },

    showPintuan: function () {
      console.log('=======');
      let that = this;
      that.setData({
        pintuanPopupState: true
      });
    },
    showPoster: function () {
      console.log('===showPoster====', getApp().globalData.clientNo);
      let that = this;
      this.getQrCode();
      that.setData({
        posterState: true,
        showWayState: false
      });
    },
    toIndex: function () {
      getApp().globalData.toIndex();
    },
    posterStateFun: function (state) {
      console.log('====state====', state);
      this.setData({
        posterState: true
      });
    },
    lookBigImage: function (e) {
      console.log("111111111", e.currentTarget.dataset);
      let imgSrc = e.currentTarget.dataset.imageurl;
      let imgArray = [];
      let index = e.currentTarget.dataset.index;
      let PostImageSrc = [];
      console.log(imgSrc);

      for (let i = 0; i < imgSrc.length; i++) {
        imgArray.push(imgSrc[i].imagePath);
        PostImageSrc.push(imgSrc[i].imagePath.replace(/http/, "https"));
      } // let PostImageSrc = imgSrc


      console.log(PostImageSrc);

      if (!imgSrc) {
        return;
      } // let urls = []
      // urls.push(imgSrc)


      wx.previewImage({
        current: imgArray[index],
        // 当前显示图片的http链接
        urls: imgArray // 需要预览的图片http链接列表

      });
    },
    showCouponState: function (e) {
      var index = e.currentTarget.dataset.id;
      this.setData({
        showState: index
      });
    },
    aaaaa: function (e) {
      console.log("hello");
      getApp().globalData.linkEvent("product_detail_9218.html");
    },
    selectFavouriteType:function(e){
        let that=this;
        let itemId=e.currentTarget.dataset.itemid;
        if(that.productData.productInfo.favorite==0){
            that.addToFavourite(itemId);
        }else{
            that.removeFavourite(itemId);
        }
    },
    /* 删除收藏 */
    removeFavourite: function (itemId) {
      var that = this; 
      getApp().globalData.showToastLoading('loading', true);
      var postData = {
        itemId: '',
        favoriteType: '1'
      };
      let productData = this.productData;
      postData.itemId = itemId;
      var customIndex = getApp().globalData.AddClientUrl("/remove_favorite.html", postData, 'post');
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log(res.data);

          if (res.data.errcode == '0') {
            productData.productInfo.favorite = 0;
            that.setData({
              productData: productData
            });
            wx.showToast({
              title: '已取消收藏！',
              image: '/wxcomponents/images/icons/tip.png',
              duration: 1000
            });
            console.log('000---' + that.productData.productInfo.favorite);
          }
        },
        fail: function (res) {
          getApp().globalData.loadFail();
        },
        complete: function (res) {
          wx.hideLoading();
        }
      });
    },

    /* 加入收藏 */
    addToFavourite: function (itemId) {
      var that = this;
      var postData = {
        itemId: '',
        favoriteType: '1'
      }; // wx.showLoading({
      //   title: 'loading'
      // })

      getApp().globalData.showToastLoading('loading', true);
      let productData = this.productData;
      postData.itemId = itemId
      console.log(postData);
      var customIndex = getApp().globalData.AddClientUrl("/add_to_favorite.html", postData, 'post');
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log(res.data);

          if (res.data.errcode == '0') {
            productData.productInfo.favorite = 1;
            that.setData({
              productData: productData
            });
            wx.showToast({
              title: '已收藏！',
              icon: 'success',
              duration: 1000
            });
            console.log('111---' + that.productData.productInfo.favorite);
          }
        },
        fail: function (res) {
          getApp().globalData.loadFail();
        },
        complete: function (res) {
          wx.hideLoading();
        }
      });
    },

    /* 查看图文详情   -- 已禁用 */
    lookDerection: function (e) {
      var images = e.currentTarget.dataset.derection;
      var sentMessage = "";

      for (let i = 0; i < images.length; i++) {
        sentMessage += "&" + i + "=" + images[i];
      }

      sentMessage = sentMessage.substring(1);
      console.log(sentMessage);
      wx.navigateTo({
        url: '/pages/productDetail_derection/index?' + sentMessage
      });
    },
    ChangeParam: function (params) {
      var returnParam = "";

      for (let i in params) {
        returnParam += "&" + i + "=" + params[i];
      }

      return returnParam;
    },

    /* dadianhua */
    callShop: function () {
      if (this.setting) {
        wx.makePhoneCall({
          phoneNumber: this.setting.platformSetting.defaultShopBean.telno //仅为示例，并非真实的电话号码

        });
      }
    },
    toCart: function (e) {
      console.warn("cart", e);
      let url = e.currentTarget.dataset.link;
      getApp().globalData.linkEvent(url); // let url ="shopping_car_list_new.html"
      // wx.navigateTo({
      //   url: '/pages/shopping_car_list_new/index'
      // })
      // app.linkEvent(url)
    },

    /* 找到购物车里面的内容 */
    findInCart: function (data) {
      var cart = null;
      this.postParams(data);
    },
    // readyPay: function (e) {
    //   this.setData({
    //     showCount: true
    //   });
    //   let info = e.currentTarget.dataset.item;
    //   this.byNowParams.productId = info.productId;
    //   this.byNowParams.shopId = info.belongShopId;
    //   this.byNowParams.orderType = 0;
    //   this.setData({
    //     byNowParams: this.byNowParams
    //   });
    // },
    readyPay2: function (e) {
      console.log('====e=====', e);

      // if (!getApp().globalData.checkIfLogin()) {
      //   return;
      // }
      if(!getApp().globalData.loginUser){
          let url="productDetail.html?id="+this.proId;
          let backUrl=encodeURIComponent(url)
          getApp().globalData.checkIfLogin(backUrl);
          return
      }
      if (this.productData.productInfo.promotionBean && this.productData.productInfo.promotionBean.promotionStatus == 2) {
        console.log('活动已结束！');
        wx.showToast({
          title: '活动已结束！',
          image: '/wxcomponents/images/icons/tip.png',
          duration: 1000
        });
        return;
      }

      let productData = this.productData;
      let way;
      let pintuanRecordId;
      console.log(productData);

      if (e.currentTarget.dataset.way) {
        way = e.currentTarget.dataset.way;
        pintuanRecordId = e.currentTarget.dataset.pintuanid;
      } else {
        way = e.detail.data.way;
        pintuanRecordId = e.detail.data.pintuanid;
      }

      this.setData({
        bindway: way
      });
      console.log('====q=====', this.bindway);
      let info = productData.productInfo;
      this.byNowParams.productId = info.productId;
      this.byNowParams.shopId = info.belongShopId;
      this.setData({
        byNowParams: this.byNowParams
      });

      if (way == 'cart') {
        if (productData.measures.length == 0) {
          this.addtocart();
        } else {
          this.setData({
            showCount: true
          });
          this.byNowParams.orderType = 0;
          this.setData({
            byNowParams: this.byNowParams
          });
          // this.chooseMeasureItem();
        }
      } else if (way == 'pintuanOne') {
        //单独购买
        this.setData({
          showCount: true
        });
        this.byNowParams.orderType = 0;
        this.pintuanParams.pintuanCreateType = 0;
        this.pintuanParams.pintuanRecordId = 0;
        this.setData({
          byNowParams: this.byNowParams,
          pintuanParams: this.pintuanParams
        });
        // this.chooseMeasureItem();
      } else if (way == 'pintuanMore') {
        //参加拼团
        this.setData({
          showCount: true
        });
        this.byNowParams.orderType = 0;
        this.pintuanParams.pintuanCreateType = 1;
        this.pintuanParams.pintuanRecordId = 0;
        this.setData({
          byNowParams: this.byNowParams,
          pintuanParams: this.pintuanParams
        });
        // this.chooseMeasureItem();
      } else if (way == 'addPintuan') {
        //发起拼单
        this.setData({
          showCount: true
        });
        this.setData({
          pintuanPopupState: false
        });
        this.byNowParams.orderType = 0;
        this.pintuanParams.pintuanCreateType = 2;
        this.pintuanParams.pintuanRecordId = pintuanRecordId;
        this.setData({
          byNowParams: this.byNowParams,
          pintuanParams: this.pintuanParams
        });
        // this.chooseMeasureItem();
      } else if (way == 'select') {
        this.setData({
          showCount: true
        });
        this.byNowParams.orderType = 0;
        this.setData({
          byNowParams: this.byNowParams
        });
        // this.chooseMeasureItem();
      } else {
        this.setData({
          showCount: true
        });
        this.byNowParams.orderType = 0;
        this.setData({
          byNowParams: this.byNowParams
        });
        // this.chooseMeasureItem();
      }
    },
    closeZhezhao: function () {
      this.setData({
        showCount: false
      });
    },
    // subNum: function () {
    //   if (this.measurementJson.id) {
    //     this.setData({
    //       minCount: this.measurementJson.minSaleCount
    //     });
    //   } else {
    //     this.setData({
    //       minCount: 1
    //     });
    //   }

    //   if (this.byNowParams.itemCount == this.minCount) {
    //     return;
    //   }

    //   this.byNowParams.itemCount--;
    //   this.setData({
    //     byNowParams: this.byNowParams
    //   });
    // },
    // addNum: function () {
    //   this.byNowParams.itemCount++;
    //   this.setData({
    //     byNowParams: this.byNowParams
    //   });
    // },

    /* 立即购买 */
    // buyNow: function (e) {
    //   if (!getApp().globalData.checkShopOpenTime()) {
    //     return;
    //   }

    //   if (!getApp().globalData.checkIfLogin()) {
    //     return;
    //   }

    //   let bindway;

    //   if (e.currentTarget.dataset.way) {
    //     bindway = e.currentTarget.dataset.way;
    //   } else {
    //     bindway = this.bindway;
    //   }

    //   console.log('=======bindway======', bindway);

    //   if (bindway == 'cart') {
    //     this.setData({
    //       haveMeasuresState: true
    //     });
    //     this.setData({
    //       selectTypeData: this.selectTypeData
    //     });
    //     console.log('-----------addtocart----------');
    //     this.addtocart();
    //   } else if (bindway == 'pintuanOne') {
    //     this.setData({
    //       haveMeasuresState: true
    //     });
    //     this.setData({
    //       selectTypeData: this.selectTypeData
    //     });
    //     console.log('-----------addtocart----------');
    //     this.createOrder22(this.byNowParams);
    //   } else if (bindway == 'pintuanMore') {
    //     this.setData({
    //       haveMeasuresState: true
    //     });
    //     this.setData({
    //       selectTypeData: this.selectTypeData
    //     });
    //     console.log('-----------addtocart----------');
    //     this.createOrder22(this.byNowParams);
    //   } else if (bindway == 'addPintuan') {
    //     this.setData({
    //       haveMeasuresState: true
    //     });
    //     this.setData({
    //       selectTypeData: this.selectTypeData
    //     });
    //     console.log('-----------addtocart----------');
    //     this.createOrder22(this.byNowParams);
    //   } else {
    //     console.log('-----------buyNow----------');
    //     this.createOrder22(this.byNowParams);
    //   }
    // },

    /* 创建订单 */
    createOrder22: function (o) {
      console.log('========createOrder22======', o);
      let that = this;
      let productInfo = that.productData.productInfo;
      let params = Object.assign({}, params, that.byNowParams, that.pintuanParams);

      if (productInfo.preOrderCustomFormId) {
        let url;

        if (that.byNowParams.cartesianId) {
          url = '/pages/form_detail/index?customFormId=' + productInfo.preOrderCustomFormId + '&productId=' + productInfo.productId + '&params=' + JSON.stringify(params);
        } else {
          url = '/pages/form_detail/index?customFormId=' + productInfo.preOrderCustomFormId + '&productId=' + productInfo.productId;
        }

        wx.navigateTo({
          url: url
        });
        return;
      } else {
        getApp().globalData.showToastLoading('loading', true);
        getApp().globalData.createOrder(that.byNowParams, that.pintuanParams);
      } 
    },

    /* 加入購物車 */
    addtocart: function () {
      if (!getApp().globalData.checkIfLogin()) {
        return;
      }

      var params = {
        cartesianId: '',
        productId: '',
        shopId: '',
        count: '',
        type: ''
      };

      if (this.productData.measures.length == 0) {
        params.cartesianId = '0';
      } else {
        params.cartesianId = this.measurementJson.id;
      }

      params.productId = this.productData.productInfo.productId;
      params.shopId = this.productData.productInfo.belongShopBean.id;
      params.count = this.byNowParams.itemCount;
      params.type = 'add';
      console.log('===postParams=====', params);
      this.postParams(params);
    },
    postParams: function (data) {
      var that = this;
      var customIndex = getApp().globalData.AddClientUrl("/change_shopping_car_item.html", data, 'post');
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log('---------------change_shopping_car_item-----------------');
          console.log(res.data);
          wx.hideLoading();

          if (that.bindway == 'cart') {
            that.setData({
              showCount: false
            });
          }

          if (data.productId == 0) {
            console.log('购物车里面的商品数量');
            that.setData({
              countGood: res.data.totalCarItemCount
            });
          } else {
            if (res.data.productId && res.data.productId != 0) {
              if (data.count == 0) {
                console.log('通过加入购物车来确定购物车里面的商品数量');
              } else {
                wx.showToast({
                  title: '加入购物车成功'
                });
              }

              if (!!res.data.totalCarItemCount || res.data.totalCarItemCount == 0) {
                that.setData({
                  countGood: res.data.totalCarItemCount
                });
              }
            } else {
              wx.showToast({
                title: res.data.errMsg,
                image: '/wxcomponents/images/icons/tip.png',
                duration: 2000
              });
            }
          }

          try {
            if (data.count == 0) {//此时购物车数量不会发生变化
            } else {
              getApp().globalData.carChangeNotify(res.data);
            }
          } catch (e) {}
        },
        fail: function (res) {
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    getPintuanData: function (productId, promotionId) {
      let that = this;
      let data = {
        status: 1,
        productId: productId,
        promotionId: promotionId
      };
      that.setData({
        pintuanParam: data
      });
      var pintuanUrl = getApp().globalData.AddClientUrl("/wx_find_pintuan_records.html", data, 'post');
      wx.request({
        url: pintuanUrl.url,
        data: pintuanUrl.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log('--------add----------');
          console.log(res.data);
          that.setData({
            pintuanListData: res.data.relateObj.result
          });

          if (that.pintuanListData.length == 1) {
            that.setData({
              visiblePintuanNum: 1
            });
          } else {
            that.setData({
              visiblePintuanNum: 2
            });
          }
        },
        fail: function (res) {
          getApp().globalData.loadFail();
        },
        complete: function () {
          wx.hideLoading();
        }
      });
    },
    getData: function (options, type) {
      let param = {};
      let that = this;

      if (!options) {
        param = that.dataFOr_getData;
      } else {
        param = options;
      }
      getApp().globalData.showToastLoading('loading', true);
      console.log('==param===', param);
      let postParam = {};
      postParam.productId = param.id || param.productId;
      postParam.addShopId = param.addShopId;
      let customIndex = getApp().globalData.AddClientUrl("/product_detail.html", postParam);
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log(res);
          that.setData({
            pintuanState: false
          });
          console.log('--------------getData-------------');
          res.data.productInfo.promotion = Number(res.data.productInfo.promotion);

          if (res.data.productInfo && res.data.productInfo.promotionBean) {
            that.setData({
              promotionState: true
            });

            if (res.data.productInfo.promotionBean.promotionStatus == 2) {
              that.setData({
                color: '#888',
                secondColor: '#fff'
              });
            }

            if (res.data.productInfo.promotionBean.pintuanStrategy && res.data.productInfo.promotionBean.pintuanStrategy.id) {
              that.setData({
                pintuanState: true
              });
              that.getPintuanData(res.data.productInfo.productId, res.data.productInfo.promotionBean.id); //获取拼团人员的数据
            }
          }

          that.setData({
            productData: res.data
          });

          if (res.data.images) {
            that.setData({
              totalImg: res.data.images.length
            });
          }

          if (res.data.productInfo && res.data.productInfo.tags) {
            let tagsStr = res.data.productInfo.tags;
            let tagsStr2 = tagsStr.replace(/\[/g, '');
            let tagArr = tagsStr2.split(']');
            tagArr.length--;
            that.setData({
              targs: tagArr
            });
            console.log('targs', that.targs);
          }

          if (res.data.description && res.data.description.description) {
            let articleJsonData=res.data.description.description;
            that.setData({
              articleJsonData: {data:{jsonData:{content:articleJsonData}}}
            });
            console.log('====articleJsonData====', that.articleJsonData);
          }

          if (res.data.productInfo.saleStrategy && res.data.productInfo.saleStrategy != 0) {
            that.setData({
              saleStrategyState: true
            });
            console.log('====saleStrategyState====', that.saleStrategyState);
          }

          if (res.data.measuresState && res.data.measuresState.length != 0) {
            that.setData({
              measuresState: true
            });
            console.log('====measuresState====', that.measuresState);
          }

          if (res.data.productInfo.latitude && res.data.productInfo.latitude != 0) {
            that.setData({
              positionState: true
            });
            console.log('====positionState====', that.positionState);
          }

          if (res.data.attrs && res.data.attrs.length != 0) {
            that.setData({
              attrsState: true
            });
            console.log('====attrsState====', that.attrsState);
          }

          if (!!res.data.productInfo) {
            let info = res.data.productInfo;
            let postPatam = {}; //var paramStr = 'page=1&productId=' + info.productId+'&shopId=' + info.belongShopId

            postPatam.page = 1;
            postPatam.productId = info.productId;
            postPatam.shopId = info.belongShopId; // that.getCommitData(postPatam)

            that.getCart();
          }

          console.log('productData', that.productData);
        },
        fail: function (res) {
          console.log("====fail====="); // app.loadFail()

          if (!type) {
            console.log("======加载失败一次======");
            that.optionsData.someOneParam = 1;
            that.getData(that.optionsData, 'lastOne');
          }
        },
        complete: function (res) {
          wx.hideLoading();
        }
      });
    },
    switchState: function (e) {
      console.log("====switchState====", e);
      let type = e.currentTarget.dataset.type;

      if (type == 1) {
        this.setData({
          showInfo: true,
          bottomState: true
        });
      } else {
        this.setData({
          showInfo: false,
          bottomState: false
        });
      }
    },
    getCart: function () {
      var params = {};
      params.productId = 0;
      params.count = 0;
      params.type = 'add';
      this.postParams(params);
    },
    onPageScroll: function (e) {
      console.log("==onPageScroll==", e); 
      // if (e.scrollTop - this.data.swiperHeight > 200 && e.scrollTop - this.data.swiperHeight < 220){
      //   this.setData({ loadingText:'即将查看详情'})
      // } else if(e.scrollTop - this.data.swiperHeight > 220){
      // }
    },
    shareAppMessage: function (res) {
      console.log(res);
      let that = this;
      that.setData({
        showWayState: false
      });
      let params = that.dataFOr_getData;
      let productItem = that.productData.productInfo;

      if (!productItem.brandName || productItem.brandName == "") {
        productItem.brandName = "";
      }

      ;
      let shareName = '活动价：￥' + productItem.price + '(原价：￥' + productItem.tagPrice + ')' + productItem.brandName + productItem.name;
      console.log('params:', params, that.productData);
      return getApp().globalData.shareForFx2('productDetail', shareName, params);
    },
    closeGuigeZhezhao: function () {
      this.setData({
        showGuigeType: false
      });
      this.MeasureParams = [];
    },
    // 获取二维码
    getQrCode: function () {
      let userId = "";

      if (getApp().globalData.loginUser && getApp().globalData.loginUser.platformUser) {
        userId = 'MINI_PLATFORM_USER_ID_' + getApp().globalData.loginUser.platformUser.id;
      }

      let postParam = {};
      postParam.SHARE_PRODUCT_DETAIL_PAGE = this.proId;
      postParam.scene = userId; // 上面是需要的参数下面的url

      console.log('====pp======', "/super_shop_manager_get_mini_code.html?mini=1&path=pageTab%2findex%2findex%3fSHARE_PRODUCT_DETAIL_PAGE%3d" + this.proId + "%26scene%3d" + userId);
      var customIndex = getApp().globalData.AddClientUrl("/super_shop_manager_get_mini_code.html?mini=1&path=pageTab%2findex%2findex%3fSHARE_PRODUCT_DETAIL_PAGE%3d" + this.proId + "%26scene%3d" + userId, postParam, 'get', '1');
      var result = customIndex.url.split("?");
      customIndex.url = result[0] + "?" + result[1];
      console.log("customIndex", customIndex.url, result[0]);
      var that = this;
      that.setData({
        qrCodeUrl: customIndex.url
      });
    },
    // 定位
    clickCatch: function (e) {
      console.log(this.productData.productInfo);
      let latitude = this.productData.productInfo.latitude;
      let longitude = this.productData.productInfo.longitude;
      let name = this.productData.productInfo.name;
      let address = this.productData.productInfo.location;
      wx.openLocation({
        latitude: latitude,
        longitude: longitude,
        scale: 12,
        name: name,
        address: address
      });
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>